package at.fhj.itm10.ticketmaster.validators;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import at.fhj.itm10.ticketmaster.dao.DAOException;
import at.fhj.itm10.ticketmaster.dao.DAOFactory;
import at.fhj.itm10.ticketmaster.dao.impl.DAOFactoryImpl;
import at.fhj.itm10.ticketmaster.models.Customer;

/**
 * checks if entered username is unique
 * 
 * @author Sabrina Gruber
 */
@FacesValidator(value="UniqueUsernameValidator")
public class UniqueUsernameValidator implements Validator {
 
	public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) {
  
	    String userName = (String) object;
	    boolean alreadyExists = false;
	  
	    try {
	    	DAOFactory daoFactory = new DAOFactoryImpl();
		    List<Customer> userList = daoFactory.getCustomerDAO().findByUsername(userName);
		    if (userList.size() > 0) {
		    	alreadyExists = true;
		    }
	    } catch (DAOException e) {
	    	e.printStackTrace();
	    }
	
	    if(alreadyExists == true) {
	    	FacesMessage message = new FacesMessage();
	    	message.setDetail("Dieser Username existiert bereits. Bitte geben Sie einen anderen ein.");
	
	    	message.setSeverity(FacesMessage.SEVERITY_ERROR);
	    	throw new ValidatorException(message);
	    }
	}
}